package com.company.tree;

import com.company.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author jrue
 * @version 1.0
 * @date 2020/1/28 14:47
 * https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
 * 给定一个 N 叉树，返回其节点值的层序遍历。 (即从左到右，逐层遍历)。
 *
 * 例如，给定一个 3叉树
 */
public class NAryTreeLevelOrderTraversal {

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);

        List<Integer> values = new ArrayList<>();
        int preNodeCount = 1;
        int thisNodeCount = 0;

        while (!queue.isEmpty()) {
            Node thisNode = queue.poll();
            preNodeCount--;
            values.add(thisNode.val);
            for (int i = 0; i < thisNode.children.size(); i++) {
                queue.offer(thisNode.children.get(i));
                thisNodeCount++;
            }

            if (preNodeCount == 0) {
                preNodeCount = thisNodeCount;
                thisNodeCount = 0;
                lists.add(values);
                values = new ArrayList<>();
            }
        }

        return lists;
    }
}
